package com.plus.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.annotation.WebFilter;
import java.util.List;

/**
 * @program: plus-easy
 * @ClassName CorsConfig
 * @description:跨域配置
 * @author: 黄涛
 * @create: 2023-12-20 14:27
 * @Version 1.0
 **/
@Component
@WebFilter(filterName = "CorsFilter",urlPatterns = "/*")
@ConfigurationProperties(prefix = "spring.security.cors")
public class CorsCFilterConfig {

    /**
     * 是否启用
     */
    private static boolean enable;
    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    /**
     * 允许的origin
     */
    private static List<String> origins;
    public void setOrigins(List<String> origins) {
        this.origins = origins;
    }

    /**
     * 允许的header
     */
    private static List<String> heads;
    public void setHeads(List<String> heads) {
        this.heads = heads;
    }

    /**
     * 允许的header
     */
    private static List<String> methods;
    public void setMethods(List<String> methods) {
        this.methods = methods;
    }


    private CorsConfiguration addCorsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //请求常用的三种配置，*代表允许所有，当时你也可以自定义属性（比如header只能带什么，只能是post方式等等）

        if(origins != null && origins.size() >0){
            for (String str : origins){
                corsConfiguration.addAllowedOrigin(str);
            }
        }else {
            corsConfiguration.addAllowedOrigin("*");
        }

        if(heads != null && heads.size() >0){
            for (String str : heads){
                corsConfiguration.addAllowedHeader(str);
            }
        }else {
            corsConfiguration.addAllowedHeader("*");
        }


        if(methods != null && methods.size() >0){
            for (String str : methods){
                corsConfiguration.addAllowedMethod(str);
            }
        }else {
            corsConfiguration.addAllowedMethod("*");
        }


        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        if(enable){
            source.registerCorsConfiguration("/**", addCorsConfig());
        }
        return new CorsFilter(source);
    }



}


